package com.xiaobaibai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobaibai.bo.OrderListSelect;
import com.xiaobaibai.common.OrderCommon;
import com.xiaobaibai.common.OrderEnum;
import com.xiaobaibai.dao.OrderDao;
import com.xiaobaibai.entity.BargainUser;
import com.xiaobaibai.entity.CouponBelong;
import com.xiaobaibai.entity.Order;
import com.xiaobaibai.entity.PayReturn;
import com.xiaobaibai.response.ResponseFormat;
import com.xiaobaibai.service.IBargainUserService;
import com.xiaobaibai.service.ICouponBelongService;
import com.xiaobaibai.service.IOrderService;
import com.xiaobaibai.service.IPayReturnService;
import com.xiaobaibai.vo.ReturnPayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaobaibai
 * @since 2020-10-16
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, Order> implements IOrderService {

    @Autowired
    private ICouponBelongService couponBelongService;

    @Autowired
    private IBargainUserService bargainUserService;

    @Autowired
    private IPayReturnService payReturnService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<Order> getListBySelect(OrderListSelect orderListSelect) {
        orderListSelect.setPageNum(orderListSelect.getPageNum()*orderListSelect.getPageSize());
        return this.baseMapper.getListBySelect(orderListSelect);
    }

    @Override
    @Transactional
    public void cancelOrder(Order order) {
        Integer userId=order.getUserId();
        Integer orderCouponId = order.getOrderCouponId();
        if(orderCouponId!=null){
            //返还优惠券
            UpdateWrapper<CouponBelong> u1=new UpdateWrapper<>();
            u1.eq("user_id",userId);
            u1.eq("coupon_id",orderCouponId);
            u1.set("status",0);//转为未使用
            couponBelongService.update(u1);//返还优惠券
        }
        Integer bargainUserId = order.getBargainUserId();
        if(bargainUserId!=null){
            //返还砍价商品
            UpdateWrapper<BargainUser> u2=new UpdateWrapper<>();
            u2.eq("id",order.getBargainUserId());
            u2.set("status",2);
            bargainUserService.update(u2);//返还砍价商品
        }
        //修改状态并且存入数据库
        //不用本类方法,防止发送异常不会回滚(但我发现,即使调用本类this.updateById出错也会回滚)
        int i = this.baseMapper.updateOrderStatus(order.getOrderId(), OrderEnum.CANCEL.getCode());
        if(i==0)
            throw new RuntimeException("取消订单失败,当前状态不可取消");
    }

    @Override
    public Map getDashboard() {
        return this.baseMapper.getDashboard();
    }

    @Override
    @Transactional
    public String agreeReturn(ReturnPayVo returnPayVo) {
        /**
         * 1.更改订单状态
         * 2.新增退款记录
         * 3.如果是待送达状态记得返还优惠券+砍价商品
         */
        QueryWrapper<Order> q1=new QueryWrapper<>();
        q1.select("order_id","order_status","user_phone","user_id","order_coupon_id","bargain_user_id","order_real_price");
        q1.eq("order_id",returnPayVo.getOrderId());
        Order order = orderService.getOne(q1);
        Integer status=order.getOrderStatus();
        if(!status.equals(OrderEnum.REFUNDING.getCode()))
            throw new RuntimeException("非[退款中]状态");

        Boolean flagCache = stringRedisTemplate.hasKey(OrderCommon.doOrderLock + order.getUserId());
        if(flagCache)
            throw new RuntimeException("与用户操作冲突,请稍后再试");
        stringRedisTemplate.opsForValue()
                .set(OrderCommon.doOrderLock+order.getUserId(),"1",10, TimeUnit.SECONDS);

        PayReturn payReturn=new PayReturn();
        payReturn.setOrderAmount(order.getOrderRealPrice());//订单总金额
        payReturn.setReason(returnPayVo.getReason());
        payReturn.setOrderId(returnPayVo.getOrderId());
        payReturn.setRefund(new BigDecimal(returnPayVo.getAmount()));
        payReturnService.save(payReturn);//新增退款记录
        UpdateWrapper<Order> u1=new UpdateWrapper<>();
        u1.eq("order_id",returnPayVo.getOrderId())
                .eq("order_status",OrderEnum.REFUNDING.getCode());
        u1.set("order_status",OrderEnum.REFUND.getCode());
        boolean flag = orderService.update(u1);
        if(!flag)
            throw new RuntimeException("同意退款失败,订单状态错误");
        String oldStatus = stringRedisTemplate.opsForValue().get("orderStatus:" + returnPayVo.getOrderId());
        if(oldStatus!=null&&oldStatus.equals("1")){//先前是等待送达状态,返还优惠券+砍价商品
            Integer orderCouponId = order.getOrderCouponId();
            if(orderCouponId!=null){
                //返还优惠券
                UpdateWrapper<CouponBelong> u2=new UpdateWrapper<>();
                u2.eq("user_id",order.getUserId());
                u2.eq("coupon_id",orderCouponId);
                u2.set("status",0);//转为未使用
                couponBelongService.update(u2);//返还优惠券
            }
            Integer bargainUserId = order.getBargainUserId();
            if(bargainUserId!=null){
                //返还砍价商品
                UpdateWrapper<BargainUser> u2=new UpdateWrapper<>();
                u2.eq("id",order.getBargainUserId());
                u2.set("status",2);
                bargainUserService.update(u2);//返还砍价商品
            }
        }
        return order.getUserPhone();
    }

}
